package com.mrd.gtimp.registered;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

public class SpellHelper {
    //将中文转换为英文
    public static String getEname(String name) throws BadHanyuPinyinOutputFormatCombination {
        HanyuPinyinOutputFormat pyFormat = new HanyuPinyinOutputFormat();
        pyFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        pyFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        pyFormat.setVCharType(HanyuPinyinVCharType.WITH_V);

        return PinyinHelper.toHanyuPinyinString(name, pyFormat, "");
    }

    /**
     * 生成登录名
     */
    public static String getAccountName(String name) throws BadHanyuPinyinOutputFormatCombination {
        char[] strs = name.toCharArray();
        String newname = null;

        //名字的长度
        if (strs.length == 2) {
            newname = getEname("" + strs[0])
                    + getEname("" + strs[1]).substring(0, 1);
        } else if (strs.length == 3) {
            newname = getEname("" + strs[0])
                    + getEname("" + strs[1]).substring(0, 1)
                    + getEname("" + strs[2]).substring(0, 1);
        } else if (strs.length == 4) {
            newname = getEname("" + strs[0] + strs[1])
                    + getEname("" + strs[2]).substring(0, 1)
                    + getEname("" + strs[3]).substring(0, 1);
        } else {
            newname = toUpCase(getEname(name));
        }

        return newname;
    }

    //首字母大写
    private static String toUpCase(String str) {
        StringBuffer newstr = new StringBuffer();
        newstr.append((str.substring(0, 1)).toUpperCase()).append(
                str.substring(1, str.length()));

        return newstr.toString();
    }

    public static void main(String[] args) {
        try {
            System.out.println(getEname("李宇春"));
        } catch (BadHanyuPinyinOutputFormatCombination e) {
            e.printStackTrace();
        }

    }

}
